package com.xysq.util;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Patterns;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.util.HashMap;
import java.util.Hashtable;

public final class QRCodeUtil {

    public static final String PARAM_ID = "id";

    public static final String PARAM_AP_ID = "apId";

    public static final String PARAM_CHANNEL_ID = "channelId";
    public static final String PARAM_RESELLER_ID = "resellerId";
    public static final String PARAM_BUSINESS_ID = "businessId";
    public static final String PARAM_CUSTOMER_ID = "customerId";

    private QRCodeUtil() {
        throw new AssertionError();
    }

    public static HashMap<String, Long> parseUrl(String urlString) {
        if (TextUtils.isEmpty(urlString)) {
            return null;
        }

        if (!Patterns.WEB_URL.matcher(urlString).matches()) {
            return null;
        }

        Uri uri = Uri.parse(urlString);
        HashMap<String, Long> params = new HashMap<String, Long>(3);
        try {
            String idParam = uri.getQueryParameter(PARAM_ID);
            String apIdParam = uri.getQueryParameter(PARAM_AP_ID);
            String channelIdParam = uri.getQueryParameter(PARAM_CHANNEL_ID);
            String resellerIdParam = uri.getQueryParameter(PARAM_RESELLER_ID);
            String businessIdParam = uri.getQueryParameter(PARAM_BUSINESS_ID);
            String customerIdParam = uri.getQueryParameter(PARAM_CUSTOMER_ID);
            if (!TextUtils.isEmpty(idParam)) {
                params.put(PARAM_ID, Long.parseLong(idParam));
            }
            if (!TextUtils.isEmpty(apIdParam)) {
                params.put(PARAM_AP_ID, Long.parseLong(apIdParam));
            }
            if (!TextUtils.isEmpty(channelIdParam)) {
                params.put(PARAM_CHANNEL_ID, Long.parseLong(channelIdParam));
            }
            if (!TextUtils.isEmpty(resellerIdParam)) {
                params.put(PARAM_RESELLER_ID, Long.parseLong(resellerIdParam));
            }
            if (!TextUtils.isEmpty(businessIdParam)) {
                params.put(PARAM_BUSINESS_ID, Long.parseLong(businessIdParam));
            }
            if (!TextUtils.isEmpty(customerIdParam)) {
                params.put(PARAM_CUSTOMER_ID, Long.parseLong(customerIdParam));
            }
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
            return null;
        } catch (NullPointerException e) {
            e.printStackTrace();
            return null;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return null;
        }
        return params;
    }

    // 生成QR图
    public static Bitmap getQrCodeImage(int QR_WIDTH, int QR_HEIGHT, String text, Bitmap logo) throws WriterException {
        try {
            // 需要引入core包
            QRCodeWriter writer = new QRCodeWriter();

            if (text == null || "".equals(text) || text.length() < 1) {
                return null;
            }

            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];


            for (int y = 0; y < QR_HEIGHT; y++) {
                for (int x = 0; x < QR_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    } else {
                        pixels[y * QR_WIDTH + x] = 0x00ffff;
                    }
                }
            }

            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);

            if (logo != null) {
                bitmap = addLogo(bitmap, logo);
            }

            return bitmap;

        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 在二维码中间添加Logo图案
     */
    private static Bitmap addLogo(Bitmap src, Bitmap logo) {
        if (src == null) {
            return null;
        }

        if (logo == null) {
            return src;
        }

        //获取图片的宽高
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }

        if (logoWidth == 0 || logoHeight == 0) {
            return src;
        }

        //logo大小为二维码整体大小的1/5
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);

            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }

}
